package com.demo.controller;


import com.demo.mybatis.entity.ThreeKingVo;
import com.demo.mybatis.service.ThreeKingService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 三国武将 前端控制器
 * </p>
 *
 * @author liumin
 * @since 2022-05-13
 */
@RestController
@RequestMapping("/threeKingVo")
public class ThreeKingController {
    @Autowired
    private ThreeKingService threeKingService;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${spring.application.name}")
    private String appName;

    @RequestMapping("/add")
    @GlobalTransactional
    public Integer add(){
        ThreeKingVo threeKingVo = new ThreeKingVo();
        threeKingVo.setName("黄埔");
        threeKingVo.setAge(50);
        threeKingVo.setHeight(180.02F);
        threeKingVo.setWeight(66.2F);
        threeKingVo.setWeapon(78);
        threeKingVo.setHorse(76);
        threeKingVo.setWisdom(84);
        threeKingVo.setIntegrity(90);
        threeKingVo.setHumane(82);
        threeKingVo.setBrave(83);
        threeKingVo.setStrict(73);
        threeKingVo.setCreateTime(LocalDateTime.now());
        threeKingService.save(threeKingVo);

        Map<String, String> req = new HashMap<>();
        req.put("id", threeKingVo.getId().toString());

        this.clientApp(this.appName, "threeKingVo/update",req);

        return threeKingVo.getId();
    }

    @RequestMapping("/update")
    public void  update(@RequestBody Map<String, String> req)  {
        Integer a = 1/0;
        Integer id = Integer.parseInt(req.get("id"));
        ThreeKingVo kingVo = threeKingService.getById(id);
        kingVo.setName("狗蛋");
        threeKingService.updateById(kingVo);
    }

    protected String clientApp(String app, String path,Map<String, String> req){
        String url = String.format("http://%s/%s", app, path);
        System.out.println(url);
        return restTemplate.postForObject(url, req, String.class);
    }
}

